package com.jiuqian.demo.web.controller;

import java.io.PrintWriter;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.jiuqian.demo.service.weixin.WxChantService;
import com.jiuqian.demo.utils.weixin.SignUtil;

/**
 *
 * @Author guoqiang
 * @Date 2017年8月18日 上午9:35:56
 * @Version 1.0
 *
 */
@Controller
@RequestMapping("/weixin")
public class WeiXinController {

	private static final Logger LOGGER = LoggerFactory.getLogger(WeiXinController.class);

	public static final String TOKEN = "hanqixuayenah";

	public static final String APP_ID = "wx5de8e8eaef66636b";

	public static final String APPSECRET = "6c83ebb41b2636d6b15c7691a858f696";

	@Autowired
	private WxChantService wxChantService;

	/**
	 * 微信服务器验签
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/security", method = { RequestMethod.GET, RequestMethod.POST })
	public void security(HttpServletRequest request, HttpServletResponse response) throws Exception {
		boolean isGet = request.getMethod().toLowerCase().equals("get");
		ServletOutputStream os = response.getOutputStream();
		try {
			if (isGet) {
				String signature = request.getParameter("signature");// 微信加密签名
				String timestamp = request.getParameter("timestamp");// 时间戳
				String nonce = request.getParameter("nonce");// 随机数
				String echostr = request.getParameter("echostr");// 随机字符串
				System.out.println("token : " + TOKEN);
				System.out.println("timestamp :" + timestamp);
				System.out.println("nonce : " + nonce);
				System.out.println("echostr : " + echostr);
				System.out.println("signature : " + signature);

				// 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
				if (SignUtil.checkSignature(TOKEN, signature, timestamp, nonce)) {
					LOGGER.info("Connect the weixin server is successful.");
					os.print(echostr);
				} else {
					LOGGER.error("Failed to verify the signature!");
				}
			} else {
				String respMessage = "异常消息！";
				try {
					respMessage = wxChantService.weixinPost(request);
					// out.write(respMessage);
					LOGGER.info("The request completed successfully");
					LOGGER.info("to weixin server " + respMessage);
				} catch (Exception e) {
					e.printStackTrace();
					LOGGER.error("Failed to convert the message from weixin!");
				}
				LOGGER.error("Failed to verify the signature!");
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error("Connect the weixin server is error.");
		} finally {
			// if (out != null || outputStream != null) {
			// out.close();
			os.close();
			// }
		}

	}
}
